package com.shanling.shanlingcontroller.ui.fragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chipsguide.lib.bluetooth.managers.BluetoothDeviceManager;
import com.linkplay.lpvr.avslib.LPAVSManager;
import com.linkplay.lpvr.avslib.LPAlexaAccount;
import com.linkplay.lpvr.blelib.manager.LPAVSBTManager;
import com.linkplay.lpvr.lpvrbean.BaseDevice;
import com.linkplay.lpvr.lpvrcallback.AuthorizationCallback;
import com.qualcomm.qti.libraries.gaia.GAIA;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.base.BaseLazyFragment;
import com.shanling.shanlingcontroller.bean.BluetoothState;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.EventCenter;
import com.shanling.shanlingcontroller.bean.MybluetoothDevice;
import com.shanling.shanlingcontroller.services.csr.GAIABREDRProvider;
import com.shanling.shanlingcontroller.services.csr.MainGaiaManager;
import com.shanling.shanlingcontroller.services.csr.VersionGaiaManager;
import com.shanling.shanlingcontroller.ui.activity.BleActivity;
import com.shanling.shanlingcontroller.ui.activity.RemindActivity;
import com.shanling.shanlingcontroller.ui.activity.TryActivity;
import com.shanling.shanlingcontroller.utils.BluetoothUtil;
import com.shanling.shanlingcontroller.utils.PreferenceUtil;
import com.shanling.shanlingcontroller.utils.ToastUtils;

import org.litepal.LitePal;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.content.Context.BLUETOOTH_SERVICE;

/**
 * Created by ch1 on 2019/10/23.
 */

public class DeviceFragment extends BaseLazyFragment implements BluetoothProfile.ServiceListener {

    @BindView(R.id.iv_alexa)
    ImageView ivAlexa;
    @BindView(R.id.iv_blestate)
    ImageView ivBlestate;
    @BindView(R.id.tv_blename)
    TextView tvBlename;
    @BindView(R.id.bt_ble)
    Button btBle;
    @BindView(R.id.pb_ble)
    ProgressBar pbBle;
    @BindView(R.id.tv_hint1)
    TextView tvHint1;
    @BindView(R.id.tv_hint2)
    TextView tvHint2;
    @BindView(R.id.iv_alexalogo)
    ImageView ivAlexalogo;
    @BindView(R.id.iv_mainlogo)
    ImageView ivMainlogo;
    private LPAlexaAccount mLPAlexaAccount;
    private LPAVSBTManager mLPAVSBTManager;
    private Runnable runnable;
    private GAIABREDRProvider mGAIABREDRProvider;
    private BluetoothHeadset bluetoothHeadset;
    private BluetoothA2dp bluetoothA2dp;
    private boolean forUser=false;
    public DeviceFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_device;
    }
    @Override
    protected void initViewsAndEvents() {
        mLPAlexaAccount = LPAVSManager.getInstance(getActivity()).getAccount();
        mLPAVSBTManager = LPAVSManager.getInstance(getActivity()).getBtManager();
        mGAIABREDRProvider=CustomApplication.getInstance().getmGAIABREDRProvider();
        runnable = new Runnable() {
            @Override
            public void run() {
                if (CustomApplication.getInstance().isConnected()) {
                    return;
                }
                ToastUtils.showLongToast(getContext(), R.string.conntect_timeout);
                pbBle.setVisibility(View.INVISIBLE);
                btBle.setVisibility(View.VISIBLE);
            }
        };
        BluetoothAdapter.getDefaultAdapter().getProfileProxy(getContext(),this,  BluetoothProfile.HEADSET);
        BluetoothAdapter.getDefaultAdapter().getProfileProxy(getContext(),this,  BluetoothProfile.A2DP);
    }
    @Override
    public void onResume() {
        super.onResume();
        setMainUI();

    }

    @Override
    protected void onLazyLoad() {

    }
    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.BLUETOOTH_STATE:
                BluetoothState state = (BluetoothState) eventCenter.getData();
                if (state == null) {
                    return;
                }
                switch (state.getState()) {
                    case Constants.CONNECTED:
                        mHandler.removeCallbacks(runnable);
                        setMainUI();
                        break;
                    case Constants.DISCONNECTED:
                        setMainUI();
                        break;
                }
                break;
            case Constants.BLE_CHANGE:
                String mac = (String) eventCenter.getData();
                doDisConnected(mac);
                break;
            case Constants.A2DP_ISCONNTECT:
                boolean isConntect= (boolean) eventCenter.getData();
                if(isConntect&&forUser){
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("weiyu","连接spp");
                            doConnectSpp(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(preferenceUtil.getBleMac()),preferenceUtil.getBleType(),getContext());
                        }
                    },6000);

                }
                break;
            case Constants.IS_BOND:
                boolean isbond = (boolean) eventCenter.getData();
                if(isbond){
                   doConnectA2dp(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(preferenceUtil.getBleMac()));
                }
                break;
            case Constants.BCAK_TO_BLUETOOTH:
                doConnected();
                break;
        }
    }

    @OnClick({R.id.tv_hint2, R.id.bt_ble})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_hint2:
                if (preferenceUtil.getBleType() != 1) {
                    return;
                }
                String trim = tvHint2.getText().toString().trim();
                String login_Amazonaccount = getString(R.string.Login_Amazonaccount);
                String connecting_device = getString(R.string.Connecting_device);
                if (trim.equals(login_Amazonaccount)) {
                    if (mLPAlexaAccount.getState() != LPAlexaAccount.LpAlexaAccountState.LP_ALEXA_ACCOUNT_VALID) {
                        mLPAlexaAccount.logIn(getActivity(), new AuthorizationCallback() {
                            @Override
                            public void onCancel() {
                                ToastUtils.showToast(getActivity(), R.string.cancle);
                            }
                            @Override
                            public void onSuccess() {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (CustomApplication.getInstance().isConnected()) {
                                            tvHint1.setVisibility(View.INVISIBLE);
                                            tvHint2.setText("Things to try");
                                        } else {
                                            tvHint1.setVisibility(View.VISIBLE);
                                            tvHint1.setText(R.string.main_hint2);
                                            tvHint2.setText(R.string.Connecting_device);
                                        }
                                        ToastUtils.showToast(getActivity(), R.string.alexa_logingsuccess);
                                    }
                                });

                            }

                            @Override
                            public void onError(Exception e) {
                                ToastUtils.showToast(getActivity(), R.string.alexa_logingfailed+e.toString());
                            }
                        });
                    }
                } else if (trim.equals(connecting_device)) {
                    readyGo(BleActivity.class);
                } else if (trim.equals("Things to try")) {
                    readyGo(TryActivity.class);
                }
                break;
            case R.id.bt_ble:
                if (CustomApplication.getInstance().isConnected()) {
                    ToastUtils.showToast(getActivity(), R.string.Disconnected);
                   doDisConnected(preferenceUtil.getBleMac());
                } else {
                    doConnected();
                }
                break;
              }
    }

    private void doConnected(){
        Log.e("weiyu","重新连接");
        if (!BluetoothUtil.isBluetoothEnable()) {
            ToastUtils.showToast(getActivity(),R.string.ble_diloghint);
            return;
        }
        mHandler.removeCallbacks(runnable);
        forUser=true;
        BluetoothDevice remoteDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(preferenceUtil.getBleMac());
        if(remoteDevice.getBondState()==10){
            try {
                Method var1 =remoteDevice.getClass().getMethod("createBond");
                var1.invoke(remoteDevice);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            if (bluetoothA2dp.getConnectionState(remoteDevice) != BluetoothProfile.STATE_CONNECTED) {
                doConnectA2dp(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(preferenceUtil.getBleMac()));
            }else {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("weiyu","连接spp");
                        doConnectSpp(remoteDevice,preferenceUtil.getBleType(),getContext());
                    }
                },6000);
            }
        }
        pbBle.setVisibility(View.VISIBLE);
        btBle.setVisibility(View.INVISIBLE);
        mHandler.postDelayed(runnable, 15* 1000);

    }

    private void doDisConnected(String mac) {
        List<MybluetoothDevice> mybluetoothDevices = LitePal.where("mac = ?", mac).find(MybluetoothDevice.class);
        int type = mybluetoothDevices.get(0).getType();
        disconnectA2dp(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac));
        switch (type) {
            case 1:
                mLPAVSBTManager.disconnect();
                break;
            case 2:
                CustomApplication.getInstance().getBluetoothDeviceManager().disconnect(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac));
                break;
            case 3:
                mGAIABREDRProvider.disconnect();
                break;
        }

        setMainUI();
    }
    public void doConnectSpp(BluetoothDevice device,int type,Context context) {
        switch (type){
            case 1:
                LPAVSBTManager btManager = LPAVSManager.getInstance(CustomApplication.getInstance()).getBtManager();
                btManager .connect(new BaseDevice(device,btManager,false));
                break;
            case 2:
                CustomApplication.getInstance().getBluetoothDeviceManager().connect(device);
                break;
            case 3:
                GAIABREDRProvider gaiabredrProvider = CustomApplication.getInstance().getmGAIABREDRProvider();
                if (gaiabredrProvider.getDevice() == null) {
                    gaiabredrProvider.connect(device.getAddress(), context);
                } else {
                    if(gaiabredrProvider.getDevice().getAddress().equals(device.getAddress())){
                        gaiabredrProvider.reconnectToDevice(context);
                    }else {
                        gaiabredrProvider.connect(device.getAddress(), context);
                    }
                }
                break;
        }


    }

    private void setMainUI() {
        boolean bleIsConnected =CustomApplication.getInstance().isConnected();
        switch (preferenceUtil.getBleType()) {
            case 1:
                ivAlexalogo.setVisibility(View.VISIBLE);
                ivMainlogo.setVisibility(View.GONE);
                ivAlexa.setVisibility(View.VISIBLE);
                int state = mLPAlexaAccount.getState();
                if (state == LPAlexaAccount.LpAlexaAccountState.LP_ALEXA_ACCOUNT_VALID) {
                    if (bleIsConnected) {
                        tvHint1.setVisibility(View.INVISIBLE);
                        tvHint2.setText("Things to try");
                    } else {
                        tvHint1.setVisibility(View.VISIBLE);
                        tvHint1.setText(R.string.main_hint2);
                        tvHint2.setText(R.string.Connecting_device);
                    }
                } else {
                    tvHint1.setVisibility(View.VISIBLE);
                    tvHint1.setText(R.string.main_hint1);
                    tvHint2.setText(R.string.Login_Amazonaccount);
                }
                break;
            case 2:
                ivAlexalogo.setVisibility(View.GONE);
                ivMainlogo.setVisibility(View.VISIBLE);
                ivMainlogo.setImageResource(R.drawable.device_img_shanling);
                ivAlexa.setVisibility(View.INVISIBLE);

                if (bleIsConnected) {
                    tvHint1.setVisibility(View.INVISIBLE);
                    tvHint2.setText("Things to try");
                } else {
                    tvHint1.setVisibility(View.VISIBLE);
                    tvHint1.setText(R.string.main_hint2);
                    tvHint2.setText(R.string.Connecting_device);
                }
                break;
            case 3:
                ivAlexalogo.setVisibility(View.GONE);
                ivMainlogo.setVisibility(View.VISIBLE);
                ivMainlogo.setImageResource(R.drawable.device_img_csr_up4);
                ivAlexa.setVisibility(View.INVISIBLE);

                if (bleIsConnected) {
                    tvHint1.setVisibility(View.INVISIBLE);
                    tvHint2.setText("Things to try");
                } else {
                    tvHint1.setVisibility(View.VISIBLE);
                    tvHint1.setText(R.string.main_hint2);
                    tvHint2.setText(R.string.Connecting_device);
                }
                break;
        }
        tvBlename.setText(preferenceUtil.getBleName());
        if (bleIsConnected) {
            ivBlestate.setImageResource(R.drawable.device_icon_link);
            btBle.setText(R.string.Disconnected);
        } else {
            ivBlestate.setImageResource(R.drawable.device_icon_unlink);
            btBle.setText(R.string.connection);
        }
        pbBle.setVisibility(View.INVISIBLE);
        btBle.setVisibility(View.VISIBLE);
    }

    public void doConnectA2dp(BluetoothDevice device) {
        try {
            Method mMethodDisconnect=BluetoothA2dp.class.getMethod("connect",
                    BluetoothDevice.class);
            Method disconnect = bluetoothHeadset.getClass().getMethod("connect", BluetoothDevice.class);
            mMethodDisconnect.invoke(bluetoothA2dp, device);
            disconnect.invoke(bluetoothHeadset,device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void disconnectA2dp( BluetoothDevice device){
        try {
             Method mMethodDisconnect=BluetoothA2dp.class.getMethod("disconnect",
                    BluetoothDevice.class);
            Method disconnect = bluetoothHeadset.getClass().getMethod("disconnect", BluetoothDevice.class);
            mMethodDisconnect.invoke(bluetoothA2dp, device);
            disconnect.invoke(bluetoothHeadset,device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        switch (profile){
            case BluetoothProfile.A2DP:
                bluetoothA2dp= (BluetoothA2dp) proxy;
                break;
            case BluetoothProfile.HEADSET:
                bluetoothHeadset= (BluetoothHeadset) proxy;
                break;
        }
    }
    @Override
    public void onServiceDisconnected(int profile) {
        switch (profile){
            case BluetoothProfile.A2DP:
                bluetoothA2dp=null;
                break;
            case BluetoothProfile.HEADSET:
                bluetoothHeadset=null;
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        BluetoothAdapter.getDefaultAdapter().closeProfileProxy( BluetoothProfile.HEADSET,bluetoothHeadset);
        BluetoothAdapter.getDefaultAdapter().closeProfileProxy(BluetoothProfile.A2DP,bluetoothA2dp);
    }


}
